<template>
  <div style="margin-left: 5px;overflow-y: scroll;margin-top: 60px">
    <el-card class="card box-card flexRow" style="height: 75px;margin-bottom: 20px;margin-top: -60px">
      <span class="mText">{{ careHomeName }}</span>
      <span style="margin-left: auto">
        <el-input
            class="input"
            suffix-icon="el-icon-search"
            v-model="keyword"
            clearable
            @keydown.enter.native="load"
        />
        <el-button class="searchBtn" @click="load">根据老人姓名搜索</el-button>
      </span>
    </el-card>
    <el-card @click.native="addNewList" class="card box-card addCard"
             :style="`cursor: ${adding ? 'default' : 'pointer'}`">
      <span v-if="!adding" class="el-icon-plus" style="font-size: 50px;margin: 15px auto"></span>
      <div v-else class="flexRow" style="width: 100%;height: 100%">
        <div class="flexColumn">
          <span class="mText" style="margin-right: 20px;font-size: 15px">选择要添加药单的老人</span>
          <el-select
              style="margin-top: 20px"
              v-model="chooseElderId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入老人名称搜索"
              :remote-method="getElders"
              :loading="loading">
            <el-option
                v-for="elder in elders"
                :key="elder.elderlyId"
                :label="elder.elderlyName"
                :value="elder.elderlyId">
              <el-row>
                <el-col :span="12">{{ elder.elderlyName }}</el-col>
                <el-col :span="4">{{ elder.sex }}</el-col>
                <el-col :span="8">{{ elder.bedNumber }}床</el-col>
              </el-row>
            </el-option>
          </el-select>
        </div>
        <div v-if="JSON.stringify(chooseElder)!=='{}'" class="flexRow" style="margin-left: 40px">
          <el-avatar shape="square" :src="chooseElder.image" style="width: 80px;height: 80px"></el-avatar>
          <div style="margin-left: 20px;display: flex;flex-direction: column">
            <span style="font-weight: bold;font-size: 25px">{{ chooseElder.elderlyName }}</span>
            <div style="margin-top: 14px">
              <span>{{ chooseElder.sex }}</span>
              <span style="margin-left: 10px">{{ chooseElder.age }}岁</span>
              <span style="margin-left: 10px">{{ chooseElder.bedNumber }}床</span>
            </div>
          </div>
        </div>
        <div class="flexColumn" style="margin-left: 40px">
          <span class="mText" style="margin-right: 20px;font-size: 15px">选择负责该药单的护工</span>
          <el-select
              style="margin-top: 20px;width: 180px"
              v-model="chooseWorkerId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入护工名称搜索"
              :remote-method="getWorkers"
              :loading="loading">
            <el-option
                v-for="worker in workers"
                :key="worker.userId"
                :label="worker.name"
                :value="worker.userId">
              <el-row>
                <el-col :span="18">{{ worker.name }}</el-col>
                <el-col :span="6">{{ worker.sex ? '男' : '女' }}</el-col>
              </el-row>
            </el-option>
          </el-select>
        </div>
        <div v-if="JSON.stringify(chooseWorker)!=='{}'" class="flexColumn" style="margin-left: 40px">
          <span style="font-weight: bold;font-size: 25px">{{ chooseWorker.name }}</span>
          <div style="margin-top: 14px">
            <span>{{ chooseWorker.sex ? '男' : '女' }}</span>
          </div>
        </div>
        <div style="margin: 0 75px 0 auto;align-self: center">
          <el-button class="btn success" @click.stop="addMedicationList" style="padding: 15px 22px">
            <i class="el-icon-check" style="font-size: 25px"/></el-button>
          <el-button class="btn danger" @click.stop="cancelNewList" style="padding: 15px 22px;margin-left: 15px">
            <i class="el-icon-close" style="font-size: 25px"/>
          </el-button>
        </div>
      </div>
    </el-card>
    <el-collapse accordion>
      <el-collapse-item v-for="(list,index) in groupedItem" :key="index">
        <template slot="title">
          <div style="display: flex;flex-direction: row;width: 100%">
            <el-avatar shape="square" :src="list[0].elder.image" style="width: 80px;height: 80px"></el-avatar>
            <div style="margin-left: 20px;display: flex;flex-direction: column">
              <span style="font-weight: bold;font-size: 25px">{{ list[0].elder.elderlyName }}</span>
              <div style="margin-top: -14px">
                <span>{{ list[0].elder.sex }}</span>
                <span style="margin-left: 10px">{{ list[0].elder.age }}岁</span>
                <span style="margin-left: 10px">{{ list[0].elder.bedNumber }}床</span>
              </div>
            </div>
            <div style="margin-left: auto;align-self: center;margin-right: 40px">
              <el-button @click.stop="openDialog(list)" class="btn success" style="padding: 15px 22px">
                <!--              <el-button @click.stop="addList(list)" class="btn success" style="padding: 15px 22px">-->
                <i class="el-icon-plus" style="font-size: 25px"/></el-button>
              <el-popconfirm title="确定删除该老人的全部药单项吗?" @confirm="delElderList(list[0].elder)">
                <el-button @click.stop slot="reference" class="btn danger" style="padding: 15px 22px;margin-left: 15px">
                  <i class="el-icon-delete" style="font-size: 25px"/>
                </el-button>
              </el-popconfirm>
            </div>
          </div>
        </template>
        <el-collapse class="medicationList" style="margin: 0 20px" :value="[0, 1]">
          <el-collapse-item v-for="(dto,index) in list" :key="index" :name="index">
            <template slot="title">
              <el-row style="width: 100%">
                <el-col v-if="dto.listNum" :span="3" style="font-size: 18px">
                  {{ dto.list[0].term === '长期' ? '长期药单' : '短期药单' }}
                </el-col>
                <el-col v-else :span="3" style="font-size: 18px">药单{{ index + 1 }}</el-col>
                <el-col :span="11" style="font-weight: lighter">
                  由护工<span style="font-weight: normal">{{ dto.nurse ? dto.nurse.name : 'unknown' }}</span>负责
                </el-col>
                <el-col v-if="dto.listNum" :span="5" style="font-weight: lighter">编号 {{ dto.listNum }}</el-col>
                <el-col v-else :span="5" style="font-weight: normal;color: var(--danger)">! 该药单暂未保存</el-col>
                <div style="float: right;margin-right: 30px">
                  <!--                  <el-button @click.stop="openDialog(dto)" class="btn success"><i class="el-icon-plus"/></el-button>-->
                  <el-popconfirm style="margin-left: 10px" v-if="dto.listNum" title="确定要删除该药单吗? "
                                 @confirm="deleteList(dto.listNum)">
                    <el-button @click.stop slot="reference" class="btn danger">
                      <i class="el-icon-delete"/>
                    </el-button>
                  </el-popconfirm>
                  <el-button v-else @click.stop="list.pop()" class="btn danger"><i class="el-icon-delete"/></el-button>
                </div>
              </el-row>
            </template>
            <el-table
                :data="dto.list"
                style="width: 100%;height: 100%;border: solid black 1px;border-radius: 0 0 7px 7px"
                :header-cell-style="{
                height: '40px'
              }"
                :row-style="{height: '62px'}">
              <el-table-column width="10px"/>
              <el-table-column
                  prop="medication.name"
                  label="药品名称">
              </el-table-column>
              <el-table-column
                  prop="medication.type"
                  label="药物剂型">
              </el-table-column>
              <el-table-column
                  prop="medication.mode"
                  label="给药途径">
              </el-table-column>
              <el-table-column
                  prop="frequency.frequency"
                  label="给药频率">
              </el-table-column>
              <el-table-column label="给药剂量">
                <template slot-scope="scope">
                  {{ scope.row.dosage }} {{ scope.row.unit }}
                </template>
              </el-table-column>
              <el-table-column
                  prop="startTime"
                  label="用药开始时间">
              </el-table-column>
              <el-table-column
                  prop="endTime"
                  label="用药结束时间">
              </el-table-column>
              <el-table-column
                  prop="term"
                  label="时效">
              </el-table-column>
              <el-table-column label="具体用药时间">
                <template slot-scope="scope">
                  {{ scope.row.takeTime ? scope.row.takeTime.split(';')[0] : '' }}
                  <span v-if="scope.row.takeTime && scope.row.takeTime.split(';')[1]">···</span>
                </template>
              </el-table-column>
              <el-table-column min-width="120" class-name="cellClass" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button-group>
                    <el-button @click="openEdit(scope)" class="btnOption primary"><span class="el-icon-edit"></span>
                    </el-button>
                    <el-popconfirm title="确定删除该药单项吗?" @confirm="deleteItem(scope.row)">
                      <el-button slot="reference" class="btnOption danger"><span class="el-icon-delete"/></el-button>
                    </el-popconfirm>
                  </el-button-group>
                </template>
              </el-table-column>
              <el-table-column width="10px"/>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-collapse-item>
      <!--药单项弹窗-->
      <!--弹窗部分-->
      <el-dialog :visible.sync="dialogOption"
                 :show-close="false"
                 ref="dialog"
                 :limit="1"
                 :modal-append-to-body='false'
                 :append-to-body="false"
                 @close="closeDialog">
        <h1 style="font-size: 24px;padding-top: 20px;color: var(--deepText)" align="center">
          {{ mode ? '添加' : '修改' }}药单项
        </h1>
        <el-divider></el-divider>
        <div style="margin: 0 10% 0;padding: 3% 5% 1%;overflow-y: scroll;height: 380px">
          <el-form ref="form" :model="medicationList" label-width="140px" label-position="left">
            <el-form-item label="服用药品">
              <el-select @change="medicationOptionChange" v-model="medicationList.medicationId" style="width: 210px">
                <el-option style="font-weight: bold" v-for="m in medications" :label="m.name" :value="m.id"
                           :key="m.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="药物剂型">
              <el-select v-model="medicationList.type" style="width: 120px">
                <el-option value="冲剂"></el-option>
                <el-option value="片剂"></el-option>
                <el-option value="栓剂"></el-option>
                <el-option value="丸剂"></el-option>
                <el-option value="胶囊剂"></el-option>
                <el-option value="颗粒剂"></el-option>
                <el-option value="气雾剂"></el-option>
                <el-option value="软膏剂"></el-option>
                <el-option value="糖浆剂"></el-option>
                <el-option value="注射剂"></el-option>
                <el-option value="口服液体剂"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="给药途径">
              <el-select v-model="medicationList.mode" style="width: 106px">
                <el-option value="口服给药"></el-option>
                <el-option value="注射给药"></el-option>
                <el-option value="舌下给药"></el-option>
                <el-option value="吸入给药"></el-option>
                <el-option value="直肠给药"></el-option>
                <el-option value="皮下给药"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="给药频率">
              <el-select @change="frequencyChange" v-model="medicationList.frequencyId" style="width: 165px">
                <el-option v-for="f in frequencies" :label="f.frequency" :value="f.id" :key="f.id">
                  <el-row>
                    <el-col :span="8" style="font-weight: bold">{{ f.abbreviation }}</el-col>
                    <el-col :span="16"> {{ f.frequency }}</el-col>
                  </el-row>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="给药剂量">
              <el-input-number style="width: 140px" v-model="medicationList.dosage" :precision="2" :step="0.1"
                               :min="0"></el-input-number>
              <el-select v-model="medicationList.unit" style="width: 100px;margin-left: 20px" placeholder="单位">
                <el-option value="g">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">g</el-col>
                    <el-col :span="10">克</el-col>
                  </el-row>
                </el-option>
                <el-option value="mg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">mg</el-col>
                    <el-col :span="10">毫克</el-col>
                  </el-row>
                </el-option>
                <el-option value="μg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">μg</el-col>
                    <el-col :span="10">微克</el-col>
                  </el-row>
                </el-option>
                <el-option value="ng">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">ng</el-col>
                    <el-col :span="10">纳克</el-col>
                  </el-row>
                </el-option>
                <el-option value="ml">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">ml</el-col>
                    <el-col :span="10">毫升</el-col>
                  </el-row>
                </el-option>
                <el-option value="μl">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">μl</el-col>
                    <el-col :span="10">微升</el-col>
                  </el-row>
                </el-option>
                <el-option value="mg/kg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">mg/kg</el-col>
                    <el-col :span="10">毫克/公斤</el-col>
                  </el-row>
                </el-option>
                <el-option value="mg/kg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">mg/kg</el-col>
                    <el-col :span="10">毫克/公斤</el-col>
                  </el-row>
                </el-option>
                <el-option value="mg/kg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">mg/kg</el-col>
                    <el-col :span="10">毫克/公斤</el-col>
                  </el-row>
                </el-option>
                <el-option value="mg/kg">
                  <el-row>
                    <el-col :span="14" style="font-weight: bold">mg/kg</el-col>
                    <el-col :span="10">毫克/公斤</el-col>
                  </el-row>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用药起始日期">
              <el-date-picker
                  value-format="yyyy-MM-dd"
                  v-model="medicationList.startTime"
                  type="date"
                  placeholder="选择开始日期时间"
                  :clearable="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="用药结束日期">
              <el-date-picker
                  value-format="yyyy-MM-dd"
                  v-model="medicationList.endTime"
                  type="date"
                  placeholder="选择结束日期时间"
                  :clearable="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="时效">
              <span>{{ termCal(medicationList.startTime, medicationList.endTime) }}</span>
            </el-form-item>
            <el-form-item v-if="medicationList.frequencyId" label="具体用药时间">
              <div v-for="(time,index) in medicationList.times" :key="index">
                <el-time-picker
                    :ref="'time'+index"
                    v-model="medicationList.times[index]"
                    value-format="HH:mm:ss"
                    :placeholder="'第'+(index+1)+'次'"
                    :picker-options="{
                    format: 'HH:mm:ss'
                  }"
                    style="width: 120px;margin-right: 20px;margin-bottom: 20px"
                    :clearable="false"
                    @input="changeValue"
                    :default-value="new Date(0, 0, 0, 12, 0, 0)">
                </el-time-picker>
              </div>

            </el-form-item>

          </el-form>
        </div>
        <el-divider/>
        <div style="display: flex;flex-direction: row">
          <el-button @click="closeDialog" class="formBtn">取消</el-button>
          <el-button @click="addOption" v-if="mode" class="formBtn">添加</el-button>
          <el-button @click="editOption" v-else class="formBtn">修改</el-button>
        </div>
      </el-dialog>
    </el-collapse>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: "MedicationList",
  data() {
    return {
      //已分组的药单信息
      list: [],
      //药单项弹窗
      dialogOption: false,
      //修改或者添加
      mode: true,
      //药单项
      medicationList: {},
      //用药频率
      frequencies: [],
      //药品信息
      medications: [],
      //分组后的信息
      groupedItem: {},
      //养老院名
      careHomeName: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).careHomeName : '',
      //搜索关键词
      keyword: '',
      //是否正在新建药单
      adding: false,
      //老人列表
      elders: [],
      loading: false,
      chooseElder: {},
      chooseElderId: '',
      //护工列表
      workers: [],
      chooseWorkerId: '',
      chooseWorker: {},
    }
  },
  methods: {
    //获取分组后的药单列表
    load() {
      this.request.get('/medication-list/get-all', {
        params: {
          careHomeName: this.careHomeName,
          keyword: this.keyword
        }
      }).then(res => {
        if (res.code === '200') {
          this.list = res.data
          this.groupedItem = Object.values(this.list.reduce((groups, item) => {
            const key = item.elder.elderlyName; // 使用elder.elderlyName字段作为键
            if (!groups[key]) {
              groups[key] = []; // 如果该分组不存在，则创建一个空数组
            }
            groups[key].push(item); // 将当前项目添加到分组中
            return groups;
          }, {}))
          this.groupedItem = this.groupedItem.sort((a, b) => {
            return a[0].elder.elderlyName.localeCompare(b[0].elder.elderlyName);
          })
        } else {
          this.$notify({
            type: 'error',
            title: '获取药单信息失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '获取药单信息失败',
          message: err
        })
      })
    },
    //删除整个药单
    deleteList(listNum) {
      this.request.delete('/medication-list/delete-batch?listNum=' + listNum).then(res => {
        if (res.code === '200') {
          this.$notify({
            type: 'success',
            title: '药单删除成功',
            message: '药单编号为' + listNum + '的药单项已全部删除'
          })
          this.load()
        } else {
          this.$notify({
            type: 'error',
            title: '药单删除失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '药单删除失败',
          message: err
        })
      })
    },
    //打开弹窗
    openDialog(list) {
      this.mode = true
      this.medicationList.dto = list
      this.medicationList.elderlyId = list[0].elder.elderlyId
      this.medicationList.nurseId = list[0].nurse.userId
      this.dialogOption = true
    },
    //关闭弹窗
    closeDialog() {
      this.medicationList = {}
      this.dialogOption = false
    },
    //添加药单项
    addOption() {
      //获取用药时间字符串
      this.medicationList.takeTime = this.medicationList.times.join(';')
      //获取目标药单的药单编号
      let term = this.termCal(this.medicationList.startTime, this.medicationList.endTime)
      let dto = this.medicationList.dto.find(d => d.list[0].term === term)
      if (dto != null) {
        this.medicationList.listNum = dto.listNum
      }
      //删除多余属性
      delete this.medicationList.times
      delete this.medicationList.dto
      //进行添加
      this.request.post('/medication-list/add', this.medicationList).then(res => {
        if (res.code === '200') {
          this.$notify({
            type: 'success',
            title: '添加成功',
            message: '药单项添加成功'
          })
          this.load()
          this.closeDialog()
        } else {
          this.$notify({
            type: 'error',
            title: '药单项添加失败',
            message: res.msg
          })
          this.closeDialog()
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '药单项添加失败',
          message: err
        })
      })
    },
    //点击药品选项
    medicationOptionChange(mId) {
      //获取对应id的药品信息
      let medication = this.medications.find(m => m.id === mId)
      this.medicationList.frequencyId = medication.frequency.id
      this.medicationList.dosage = medication.dosage
      this.medicationList.unit = medication.unit
      this.medicationList.type = medication.type
      this.medicationList.mode = medication.mode
      //调用频率变动的方法
      this.frequencyChange()
    },
    //打开编辑栏
    openEdit(scope) {
      this.mode = false
      //获取数据
      this.medicationList = scope.row
      this.medicationList.medicationId = this.medicationList.medication.id
      this.medicationList.frequencyId = this.medicationList.frequency.id
      //打开窗口
      this.dialogOption = true
      //调用频率变动
      this.frequencyChange()
      //获取时间
      if (this.medicationList.takeTime.endsWith(';')) {
        this.medicationList.takeTime = this.medicationList.takeTime.slice(0, -1)
      }
      this.medicationList.times = this.medicationList.takeTime ? this.medicationList.takeTime.split(';') : ''
    },
    //修改药单项
    editOption() {
      //获取用药时间字符串
      this.medicationList.takeTime = this.medicationList.times.join(';')
      //删除多余属性
      delete this.medicationList.times
      delete this.medicationList.medication
      delete this.medicationList.frequency
      delete this.medicationList.term

      this.request.put('/medication-list/update', this.medicationList).then(res => {
        if (res.code === '200') {
          this.$notify({
            type: 'success',
            title: '成功',
            message: '修改药单项成功'
          })
          //修改药单项
          this.load()
          this.closeDialog()
        } else {
          this.$notify({
            type: 'error',
            title: '修改药单项失败',
            message: res.msg
          })
          this.load()
          this.closeDialog()
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '修改药单项失败',
          message: err
        })
      })
    },
    //修改弹窗中的频率时
    frequencyChange() {
      this.medicationList.times = new Array(this.frequencies.find(fre => fre.id === this.medicationList.frequencyId).value)
      this.$forceUpdate()
    },
    //修改时间选择器的值
    changeValue() {
      this.$forceUpdate()
    },
    //添加药单
    addList(list) {
      //如果药单已有两个，则不允许添加
      if (list.length >= 2) {
        this.$notify({
          type: 'warning',
          title: '药单添加失败',
          message: '该老人已有两个药单'
        })
        return
      }
      //添加
      list.push({
        elder: list[0].elder,
        nurse: list[0].nurse,
        list: []
      })
    },
    //删除药单项
    deleteItem(medicationList) {
      this.request.delete('/medication-list/delete?id=' + medicationList.id).then(res => {
        if (res.code === '200') {
          this.$notify({
            type: 'success',
            title: '药单项删除成功',
            message: '该药单项已被删除'
          })
          this.load()
        } else {
          this.$notify({
            type: 'error',
            title: '药单项删除失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '药单项删除失败',
          message: err
        })
      })
    },
    //添加新的老人的药单
    addNewList() {
      if (!this.adding) {
        this.adding = true
      }
    },
    //删除该老人的所有药单项
    delElderList(elder) {
      this.request.delete('/medication-list/delete-elder?elderId=' + elder.elderlyId).then(res => {
        if (res.code === '200') {
          this.$notify({
            type: 'success',
            title: '药单项删除成功',
            message: elder.elderlyName + '所属的药单项已全部删除'
          })
          this.load()
        } else {
          this.$notify({
            type: 'error',
            title: '获取频率信息失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '获取频率信息失败',
          message: err
        })
      })
    },
    //获取未分配药单的老人列表
    getElders(query) {
      console.log(query)
      if (query !== '') {
        this.loading = true
        clearTimeout(this.eldersTimer);
        this.eldersTimer = setTimeout(() => {
          if (this.eldersCancelToken) {
            this.eldersCancelToken.cancel();
          }
          this.eldersCancelToken = axios.CancelToken.source();
          this.request.get('/elderly-information/query-no-ml?careHomeName=' + this.careHomeName, {
            cancelToken: this.eldersCancelToken.token
          }).then(res => {
            if (res.code === '200') {
              console.log(res.data)
              this.elders = res.data.filter(elder => {
                return elder.elderlyName.indexOf(query) > -1;
              })
            } else {
              this.$notify({
                type: 'error',
                title: '获取老人列表失败',
                message: res.msg
              })
            }
            this.loading = false
          }).catch(err => {
            this.$notify({
              type: 'error',
              title: '获取老人列表失败',
              message: err
            })
            this.loading = false
          })
        }, 2000)
      } else {
        this.elders = []
      }
    },
    getWorkers(query) {
      if (query !== '') {
        this.loading = true
        clearTimeout(this.workersTimer);
        this.workersTimer = setTimeout(() => {
          if (this.workersCancelToken) {
            this.workersCancelToken.cancel();
          }
          this.workersCancelToken = axios.CancelToken.source();
          this.request.get('/user/query-worker?careHomeName=' + this.careHomeName, {
            cancelToken: this.workersCancelToken.token
          }).then(res => {
            if (res.code === '200') {
              this.workers = res.data;
              /*this.workers = res.data.filter(worker => {
                return worker.name.indexOf(query) > -1;
              })*/
            } else {
              this.$notify({
                type: 'error',
                title: '获取护工列表失败',
                message: res.msg
              })
            }
            this.loading = false
          }).catch(err => {
            this.$notify({
              type: 'error',
              title: '获取护工列表失败',
              message: err
            })
            this.loading = false
          })
        }, 200)
      } else {
        this.workers = []
      }
    },
    //取消新建药单
    cancelNewList() {
      this.elders = []
      this.workers = []
      this.chooseElderId = ''
      this.chooseWorkerId = ''
      this.chooseElder = {}
      this.chooseWorker = {}
      this.adding = false
    },
    //为新的老人添加药单
    addMedicationList() {
      if (JSON.stringify(this.chooseElder) === '{}') {
        this.$notify({
          type: 'error',
          title: '添加药单失败',
          message: '请先选择药单所属的老人'
        })
        return
      }
      if (JSON.stringify(this.chooseWorker) === '{}') {
        this.$notify({
          type: 'error',
          title: '添加药单失败',
          message: '请先选择负责此药单的护工'
        })
        return
      }
      this.groupedItem.unshift([{
        elder: this.chooseElder,
        nurse: this.chooseWorker,
        listNum: '',
        list: []
      }])
      this.$forceUpdate()
      this.cancelNewList()
    },
    //计算时效
    termCal(start, end) {
      if (start == null || end == null) {
        return null
      }
      let s = Date.parse(start)
      let e = Date.parse(end)
      let timeDifference = e - s
      let t = timeDifference >= (24 * 60 * 60 * 1000 * 5)
      return t ? '长期' : '短期'
    }

  },
  watch: {
    chooseElderId(value) {
      if (value !== '') {
        this.chooseElder = this.elders.find(elder => elder.elderlyId === value)
      }
    },
    chooseWorkerId(value) {
      if (value !== '') {
        this.chooseWorker = this.workers.find(worker => worker.userId === value)
      }
    }
  },
  mounted() {
    this.load()

    //获取全部频率信息
    this.request.get('/medication-frequency/getAll').then(res => {
      if (res.code === '200') {
        this.frequencies = res.data
      } else {
        this.$notify({
          type: 'error',
          title: '获取频率信息失败',
          message: res.msg
        })
      }
    }).catch(err => {
      this.$notify({
        type: 'error',
        title: '获取频率信息失败',
        message: err
      })
    })

    //获取所有药品信息
    this.request.get('/medication/getAll?careHomeName=' + this.careHomeName).then(res => {
      if (res.code === '200') {
        this.medications = res.data
      } else {
        this.$notify({
          type: 'error',
          title: '获取药品信息失败',
          message: res.msg
        })
      }
    }).catch(err => {
      this.$notify({
        type: 'error',
        title: '获取药品信息失败',
        message: err
      })
    })
  },
}
</script>

<style scoped>

/*收缩框样式*/
>>> .el-collapse-item__wrap {
  border: none;
  background-color: var(--deepBg);
}

>>> .el-collapse {
  border: none;
}

>>> .el-collapse-item__content {
  background-color: var(--lightBg);
  border-radius: 0 0 10px 10px;
  padding-bottom: 20px;
  padding-top: 10px;
  border: solid var(--inputBorder);
  border-width: 0 1px 1px 1px;
}

>>> .el-collapse-item__header {
  color: var(--deepText);
  background-color: var(--lightBg);
  height: 120px;
  transition: 0.3s;
  padding: 10px 20px;
  margin-top: 20px;
  border-radius: 10px;
  border: 1px var(--inputBorder) solid;
}

>>> .el-collapse-item__header.is-active {
  border-radius: 10px 10px 0 0;
}

>>> .medicationList .el-collapse-item__content {
  border-radius: 0 0 7px 7px;
  border: none;
  padding-bottom: 0;
  padding-top: 0;
}

>>> .medicationList .el-collapse-item__header {
  height: 80px;
  background-color: var(--btn);
  color: var(--btnText);
  border-radius: 7px;
  padding-left: 20px;
  margin-top: 10px;
  border: none;
}

>>> .medicationList .el-collapse-item__header.is-active {
  border-radius: 7px 7px 0 0;
}

>>> .el-collapse-item__arrow {
  font-size: 25px;
  font-weight: bolder;
}

>>> .medicationList .el-collapse-item__arrow {
  font-size: 20px;
}

/*表格样式*/
/*表头背景*/
>>> .el-table .cell {
  height: 20px;
}

>>> .el-table th {
  background-color: var(--deepBg) !important;
}

/*表头文字*/
>>> .el-table thead {
  color: var(--th)
}

/*背景*/
>>> .el-table tr {
  background-color: var(--deepBg);
  color: var(--deepText);
  font-weight: normal;
}

/*行间线*/
>>> .el-table td, .building-top .el-table th.is-leaf {
  border-bottom: 0 !important;
}

/*表格末尾*/
>>> .el-table::before {
  border-bottom: 0;
  height: 0;
}

>>> .el-table, .el-table__expanded-cell {
  background-color: var(--deepBg) !important;
}

/*鼠标悬浮*/
>>> .el-table tbody tr:hover > td {
  background-color: var(--hover) !important;
}

/*操作列样式*/
>>> td.cellClass .cell {
  height: 34px !important;
}

/*其他样式*/
.btn {
  color: var(--btnText);
  transition: 0.2s;
  border: none;
  padding: 10px 16px;
  font-size: 18px;
}

.danger {
  background-color: var(--danger);
}

.danger:hover {
  background-color: var(--dangerHover);
}

.success {
  background-color: var(--success);
}

.success:hover {
  background-color: var(--successHover);
}

/*弹窗样式*/
>>> .el-dialog {
  background-color: var(--lightBg);
  border-radius: 10px;
  height: 550px;
  width: 700px;
  margin-top: calc(20% - 200px) !important;
}

>>> .el-dialog__body {
  height: 100%;
  padding: 0;
}

>>> .el-dialog__header {
  height: 0;
  padding: 0;
}

>>> .el-dialog__wrapper {
  transition-duration: 0.3s;
}

>>> .dialog-fade-enter-active {
  animation: none !important;
}

>>> .dialog-fade-leave-active {
  transition-duration: 0.15s !important;
  animation: none !important;
}

>>> .dialog-fade-enter-active .el-dialog,
.dialog-fade-leave-active .el-dialog {
  animation-fill-mode: forwards;
}

>>> .dialog-fade-enter-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-open;
  animation-timing-function: cubic-bezier(0.6, 0, 0.4, 1);
}

>>> .dialog-fade-leave-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-close;
}

@keyframes anim-open {
  0% {
    opacity: 0;
    transform: scale3d(0, 0, 1);
  }
  100% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

@keyframes anim-close {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: scale3d(0.5, 0.5, 1);
  }
}

/*分割线*/
>>> .el-divider {
  background-color: var(--divider);
  width: 90%;
  height: 2px;
  margin: auto;
}

/*输入框样式*/
.input {
  margin-right: 20px;
  width: 360px;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
}

>>> .el-input__inner {
  color: var(--deepText);
  background-color: var(--inputBg);
  border: solid 1px var(--inputBorder);
  border-radius: 5px;
}

>>> .el-input__inner:focus {
  border-color: var(--btn) !important;
}

>>> .el-input__inner::placeholder {
  color: var(--lightText);
}

>>> .el-select__caret {
  color: var(--deepText) !important;
}

>>> .el-input__icon {
  color: var(--deepText);
}

/*计数器样式*/
>>> .el-input-number__decrease, >>> .el-input-number__increase {
  background-color: var(--btn);
  color: var(--btnText);
  border: none;
}

>>> .el-input-number__decrease:hover, >>> .el-input-number__increase:hover {
  background-color: var(--btnActive);
  color: var(--btnText);
}

/*表单按钮样式*/
.formBtn {
  color: var(--btnText);
  margin: 20px auto;
  width: 140px;
  height: 40px;
  background-color: var(--btn);
  transition: 0.2s;
  font-size: 13px;
  font-weight: bold;
  border: none;
}

.formBtn:hover {
  background-color: var(--btnActive);
}

/*日期选择器样式*/
>>> .el-date-editor .el-input__inner {
  cursor: pointer;
}

/*按钮*/
.btnOption {
  transition: 0.2s;
  padding: 10px 15px;
  color: var(--btnText);
  margin: 0;
  border: none;
}

.primary {
  background-color: var(--btn);
}

.primary:hover {
  background-color: var(--btnActive);
}

::-webkit-scrollbar {
  overflow: auto;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  background-color: var(--th);
  border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: var(--lightText);
}

>>> .el-form-item__label {
  color: var(--deepText)
}

/*card*/
>>> .el-card__header {
  border-color: var(--deepText);
}

>>> .el-card__body {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
}

.box-card:hover {
  background-color: var(--hover);
}

.card {
  background-color: var(--lightBg);
  border: 1px solid var(--inputBorder);
  color: var(--deepText);
}

/*搜索按钮*/
.searchBtn {
  font-size: 13px;
  font-weight: bold;
  background-color: var(--btn);
  color: var(--btnText);
  border: none;
  transition: 0.2s;
}

.searchBtn:hover {
  background-color: var(--btnActive);
}

.searchBtn::before {
  display: none;
}

.mText {
  font-size: 18px;
  color: var(--deepText);
}

.card:hover .el-icon-plus {
  color: var(--btn);
}

.addCard {
  border-radius: 10px;
  height: 120px
}
</style>